package bm.com.ai.server.LLModel.factory;

import bm.com.ai.server.LLModel.config.GlobalAiConfig;
import bm.com.ai.server.LLModel.constant.ModelType;
import bm.com.ai.server.dto.MessageRequest;
import bm.com.ai.server.LLModel.strategy.ModelStrategy;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class ModelFactory {

    @Autowired
    private List<ModelStrategy> strategies; //大模型池

    @Resource
    GlobalAiConfig globalAiConfig; //大模型全局配置

    private Map<ModelType, ModelStrategy> strategyMap = new HashMap<>();;

    private ModelStrategy defaultStrategy;

    // 初始化，首先加载所有的模型
    @PostConstruct
    public void initialize() {

        // 初始化策略映射
        for (ModelStrategy strategy : strategies) {
            strategy.initialize();
            strategyMap.put(strategy.getModelType(), strategy);
        }

        // 确定默认策略
        ModelType defaultModelType = ModelType.fromString(globalAiConfig.getDefaultModel());
        if (defaultModelType != null && strategyMap.containsKey(defaultModelType)) {
            defaultStrategy = strategyMap.get(defaultModelType);
        } else if (!strategyMap.isEmpty()) {
            // 如果没有配置默认模型或默认模型不可用，使用第一个可用模型
            defaultStrategy = strategyMap.values().iterator().next();
        }

        // 获取是否有默认的模型
        if (defaultStrategy != null) {
            log.info("Default AI model strategy set to: {}", defaultStrategy.getModelType());
        } else {
            log.warn("No AI model strategies available");
        }
    }

    /**
     * 根据请求获取对应的策略
     */
    public ModelStrategy getStrategy(MessageRequest request) {
        // 1. 如果请求指定了模型类型，尝试使用该模型
        if (request.getModelType() != null && strategyMap.containsKey(request.getModelType())) {
            ModelStrategy strategy = strategyMap.get(request.getModelType());
            if (strategy.supports(request) && strategy.isHealthy()) {
                return strategy;
            }
        }

        // 2. 尝试使用默认模型
        if (defaultStrategy != null && defaultStrategy.supports(request) && defaultStrategy.isHealthy()) {
            return defaultStrategy;
        }

        // 3. 尝试找到其他支持该请求的健康模型
        for (ModelStrategy strategy : strategyMap.values()) {
            if (strategy.supports(request) && strategy.isHealthy()) {
                return strategy;
            }
        }

        // 4. 如果所有模型都不支持或不健康，尝试返回任意已初始化的模型作为最后的手段
        for (ModelStrategy strategy : strategyMap.values()) {
            if (strategy.isHealthy()) {
                return strategy;
            }
        }

        throw new IllegalStateException("No available AI model strategy to process the request");
    }

    /**
     * 根据模型类型获取策略
     */
    public ModelStrategy getStrategy(ModelType modelType) {
        if (modelType == null) {
            return defaultStrategy;
        }

        ModelStrategy strategy = strategyMap.get(modelType);
        return strategy != null ? strategy : defaultStrategy;
    }

    /**
     * 获取所有可用模型类型
     */
    public List<ModelType> getAvailableModelTypes() {
        return strategyMap.keySet().stream()
                .filter(type -> strategyMap.get(type).isHealthy())
                .toList();
    }

}
